#include <iostream>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h> 
int ticket=1000;

class Sem
{
  public:
    Sem(int num=1)
    {
      sem_init(&sem,0,num); 
    }

    ~Sem()
    {
      sem_destroy(&sem);
    }

    void P()
    {
      sem_wait(&sem);
    }

    void V()
    {
      sem_post(&sem);
    }
  private:
    sem_t sem;
};

Sem sem;
void* buyTicket(void* arg)
{
  while(1)
  {
    sem.P();
    if(ticket>0)
    {
      printf("%s:%d\n",(char*)arg,ticket);
      ticket--;
      usleep(100);
      sem.V();
    }
    else 
    {
      sem.V();
      break;
    }
  }
  return 0;
}


int main()
{
  pthread_t thread1,thread2,thread3;
  pthread_create(&thread1,nullptr,buyTicket,(void*)"thread1");
  pthread_create(&thread2,nullptr,buyTicket,(void*)"thread2");
  pthread_create(&thread3,nullptr,buyTicket,(void*)"thread3");

  pthread_join(thread1,nullptr);
  pthread_join(thread2,nullptr);
  pthread_join(thread3,nullptr);
  return 0;
}
